//导入数据库API
const db = require('../../config/db')
// 导入加密/解密文件
const aes2 = require('../../utils/aes2');
// 导入jwt token工具
const JwtUtil = require('../../utils/jwt');
// 正在表达式
const rep_phone = /^1[3-9]\d{9}$/;
const rep_email = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
// 默认头像 , 例如： http://localhost:3000/imgs/1.jpg
let {
    HOST_URL
} = require('../../config/host');

let user_avators = [
    "/imgs/1.jpg",
    "/imgs/2.jpg",
    "/imgs/3.jpg",
    "/imgs/4.jpg",
    "/imgs/5.jpg",
    "/imgs/6.jpg"
]
let rd = () => {
    return Math.floor(Math.random() * user_avators.length);
}

// 封装注册接口
const register = (user_id, user_acc, user_pwd, user_nick_name, user_create_time) => {
    return new Promise((resolve, reject) => {
        let user_check_sql = `select * from db_user where user_acc = "${user_acc}"`
        db.query(user_check_sql, (error, result) => {
            if (error) {
                reject({
                    code: -1,
                    msg: '查询用户异常。'
                })
            } else {
                // result: 数组
                // result.length == 0 该账号还没被注册
                if (result.length == 0) {
                    let pwd = aes2.aesEncrypt(user_pwd) //加密
                    let avator = HOST_URL + user_avators[rd()]; // 用户默认头像
                    let user_insert_sql = `insert into db_user(user_id,user_acc,user_pwd,user_nick_name,user_create_time,user_avator) values("${user_id}","${user_acc}","${pwd}","${user_nick_name}","${user_create_time}","${avator}")`;
                    db.query(user_insert_sql, (err, rows) => {
                        if (err) {
                            reject({
                                code: -1,
                                msg: '用户注册失败。',
                                err
                            })
                        } else {
                            resolve({
                                code: 200,
                                msg: '用户注册成功。',
                                user_nick_name,
                                result
                            })
                        }
                    })
                } else {
                    resolve({
                        code: 201,
                        msg: '该账号已经存在。',
                        result
                    })
                }
            }
        })
    })
}

// 封装用户登录接口
// 设置用户登录的有效时间
// 把用户的user_id生产临时的随机字符串(token)
// token: 临时身份（令牌）
const login = (user_acc, user_pwd) => {
    return new Promise((resolve, reject) => {

        // 查询用户表sql语句
        let user_check_sql = ''
        // 判断用户输入的是邮箱还是手机
        if (rep_email.test(user_acc)) {
            user_check_sql = `select * from db_user where user_acc="${user_acc}"`;
        } else
        if (rep_phone.test(user_acc)) {
            user_check_sql = `select * from db_user where user_phone="${user_acc}"`;
        }

        // console.log("6.0", user_acc, user_pwd);
        db.query(user_check_sql, (err, rows) => {
            if (err) {
                resolve({
                    code: -1,
                    msg: '账号或密码错误。',

                })
            } else {
                if (rows.length == 1) {
                    // 匹配密码
                    // 参数1：前端提交的密码，参数2：数据库的密码
                    // console.log('7.0', aes2.aesDecrypt(user_pwd, rows[0]['user_pwd']));
                    if (aes2.aesDecrypt(user_pwd, rows[0]['user_pwd'])) {
                        let [{
                            user_id,
                            user_nick_name,
                            user_acc,
                            user_phone,
                            user_avator
                        }] = rows;
                        // 将用户id传入并生成token
                        let jwt = new JwtUtil(user_id);
                        // 获取token
                        let token = jwt.generateToken();
                        // 定义用户对象
                        let user = {
                            code: 200,
                            msg: '恭喜您,登录成功。',
                            token,
                            user_nick_name,
                            user_acc,
                            user_avator
                        }
                        if (user_phone) {
                            user['user_phone'] = user_phone
                        }
                        // 将 token 等信息反馈给客户端
                        resolve(user);
                    } else {
                        resolve({
                            code: -1,
                            msg: '账号或密码错误1'
                        })
                    }
                } else if (rows.length == 0) {
                    resolve({
                        code: -1,
                        msg: '账号不存在。'
                    })
                } else {
                    resolve({
                        code: 500,
                        msg: '系统异常。'
                    })
                }
            }
        })
    })
}
//操作数据库的业务
module.exports = {
    // 示例：
    test() {
        return new Promise((resolve, reject) => {

        })
    },
    // 注册接口(没有邮箱验证)
    register(user_id, user_acc, user_pwd, user_nick_name, user_create_time) {
        // 以后需要用到邮箱验证码
        // To do ....
        return register(user_id, user_acc, user_pwd, user_nick_name, user_create_time);
    },

    // 登录接口(没有邮箱验证)
    login(user_acc, user_pwd) {
        // To do ....
        return login(user_acc, user_pwd);
    },

    // 注册接口(有邮箱验证)
    register2(user_id, user_acc, user_pwd, user_nick_name, user_create_time, email_code) {
        // 需要用邮箱验证码
        return new Promise((resolve, reject) => {
            let vercode_sql = `select v1 from db_code where v1="${email_code}"`;
            db.query(vercode_sql, (err, rows) => {
                if (err) {
                    // console.log("邮箱验证码查询失败:",err);
                    reject({
                        code: -1,
                        msg: '邮箱验证码查询失败。'
                    })
                } else {
                    // console.log("rows:",rows)
                    // console.log("length:",rows.length)
                    if (rows.length == 1) {
                        // 注册用户账号
                        register(user_id, user_acc, user_pwd, user_nick_name, user_create_time).then(
                            res => {
                                resolve(res);
                            }
                        ).catch(
                            err => {
                                reject(err);
                            }
                        )
                    } else {
                        resolve({
                            code: -1,
                            msg: '邮箱验证码查询异常,请重新发送验证码。'
                        })
                    }
                }
            })
        })
    },

    // 登录接口(有邮箱验证)
    login2(user_acc, user_pwd, email_code) {
        // 需要邮箱验证码
        return new Promise((resolve, reject) => {
            let vercode_sql = `select v1 from db_code where v1="${email_code}"`;
            db.query(vercode_sql, (err, rows) => {
                if (err) {
                    // console.log("邮箱验证码查询失败:",err);
                    reject({
                        code: -1,
                        msg: '邮箱验证码查询失败。'
                    })
                } else {
                    if (rows.length == 1) {
                        // 用户账号登录
                        login(user_acc, user_pwd).then(
                            res => {
                                resolve(res);
                            }
                        ).catch(
                            err => {
                                reject(err);
                            }
                        )
                    } else {
                        resolve({
                            code: -1,
                            msg: '邮箱验证码查询异常,请重新发送验证码。'
                        })
                    }
                }
            })
        })
    },

    // 修改用户头像（上传图片）
    modify_avator(user_id, user_avator) {
        // console.log({user_id, user_avator});
        return new Promise((resolve, reject) => {
            let usr_check_sql = `select * from db_user where user_id = "${user_id}"`;
            db.query(usr_check_sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: '查询用户失败',
                        err
                    })
                } else {
                    if (rows.length == 1) {
                        let user_modify_sql = `update db_user set user_avator= "${user_avator}" where user_id= "${user_id}"`;
                        db.query(user_modify_sql, (error, result) => {
                            // console.log('9.0',{user_id, user_avator,error});
                            if (error) {
                                reject({
                                    code: -1,
                                    msg: "修改用户头像失败。",
                                    error
                                })
                            } else {
                                resolve({
                                    code: 200,
                                    msg: "修改用户头像成功。",
                                    user_avator
                                })
                            }
                        })
                    }
                }
            })
        })
    },

    // 修改用户资料
    modify(user_id, user_age, user_address, user_phone, user_sex, user_nick_name) {
        return new Promise((resolve, reject) => {
            var modify_info_sql = `update db_user set user_address= "${user_address}", user_age= "${user_age}", user_phone= "${user_phone}",user_sex= "${user_sex}",user_nick_name= "${user_nick_name}" where  user_id= "${user_id}"`;
            db.query(modify_info_sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: "修改用户资料失败。",
                        err
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: "修改用户资料成功。"
                    })
                }
            })
        })
    },

    // 获取用户头像和昵称
    get_avator_nickname(user_id) {
        return new Promise((resolve, reject) => {
            let sql = `select user_avator,user_nick_name from db_user where user_id = "${user_id}"`;
            db.query(sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: '获取头像昵称失败。'
                    })
                } else {
                    reject({
                        code: 200,
                        msg: '获取头像昵称成功。',
                        data: rows
                    })
                }
            })
        })
    },

    // 删除账号
    remove(user_id, user_acc) {
        return new Promise((resolve, reject) => {
            let user_check_sql = `select user_acc from  db_user where user_id = "${user_id}" and user_acc="${user_acc}"`
            db.query(user_check_sql, (error, result) => {
                if (error) {
                    reject({
                        code: -1,
                        msg: "查询用户失败0。",
                        err
                    })
                } else {
                    if (result.length == 1) {
                        let user_remove_sql = `delete from  db_user where user_id = "${user_id}" and user_acc="${user_acc}"`
                        db.query(user_remove_sql, (err, rows) => {
                            if (err) {
                                reject({
                                    code: -1,
                                    msg: "删除用户失败1。",
                                    err
                                })
                            } else {
                                resolve({
                                    code: 200,
                                    msg: "删除用户成功。"
                                })
                            }
                        })
                    } else {
                        reject({
                            code: -1,
                            msg: "删除用户失败2。",
                            err
                        })
                    }
                }
            })
        })
    },

    // 查询账号详情
    detail(user_id, user_acc) {
        return new Promise((resolve, reject) => {
            let user_check_sql = `select user_acc,user_age,user_sex,user_avator,user_create_time from  db_user where user_id = "${user_id}" and user_acc="${user_acc}"`
            db.query(user_check_sql, (error, result) => {
                if (error) {
                    reject({
                        code: -1,
                        msg: "查询用户失败0。",
                        err
                    })
                } else {
                    if (result.length == 1) {
                        resolve({
                            code: 200,
                            msg: "查询用户详情成功。",
                            data: result[0]
                        })
                    } else {
                        reject({
                            code: -1,
                            msg: "查询用户详情失败。",
                            err
                        })
                    }
                }
            })
        })
    },

    //查询用户列表
    // list(callback) {
    //     //sql语句
    //     let sql = "select * from db_user";
    //     //执行query方法
    //     db.query(sql, (err, rows) => {
    //         callback(err, rows)
    //     })
    // },
    // list2() {
    //     return new Promise((resolve, reject) => {
    //         //sql语句
    //         let sql = "select * from db_user";
    //         //执行query方法
    //         db.query(sql, (err, rows) => {
    //             if (err) {
    //                 reject({
    //                     code: -1,
    //                     err
    //                 });
    //             } else {
    //                 resolve({
    //                     code: 200,
    //                     rows
    //                 })
    //             }
    //         })
    //     })
    // },
    // //根据user_id查询用户表
    // detail() {
    //     return new Promise((resolve, reject) => {
    //         //编写sql语句
    //         let sql = `select * from db_coffee_hot`
    //         db.query(sql, (err, rows) => {
    //             if (err) {
    //                 reject({
    //                     code: -1,
    //                     err
    //                 })
    //             } else {
    //                 resolve({
    //                     code: 200,
    //                     result: rows
    //                 })
    //             }
    //         })
    //     })
    // },
    // // 增加
    // add(user_id, user_acc, user_pwd, user_nick_name) {
    //     return new Promise((resolve, reject) => {
    //         let sql = `insert into db_user(user_id,user_acc,user_pwd,user_nick_name) values ("${user_id}","${user_acc}","${user_pwd}","${user_nick_name}")`;
    //         db.query(sql, (err, rows) => {
    //             if (err) {
    //                 reject({
    //                     code: -1,
    //                     msg: "添加用户失败。",
    //                     err
    //                 })
    //             } else {
    //                 resolve({
    //                     code: 200,
    //                     msg: "添加用户成功。",
    //                     user_acc,
    //                     user_nick_name
    //                 })
    //             }
    //         })
    //     })
    // },
    // // 修改
    // modify(user_id, user_acc, user_pwd, user_nick_name) {
    //     return new Promise((resolve, reject) => {
    //         var sql = `update db_user set user_acc= "${user_acc}",user_pwd= "${user_pwd}",user_nick_name= "${user_nick_name}" where  user_id= "${user_id}"`;
    //         db.query(sql, (err, rows) => {
    //             if (err) {
    //                 reject({
    //                     code: -1,
    //                     msg: "修改用户资料失败。",
    //                     err
    //                 })
    //             } else {
    //                 resolve({
    //                     code: 200,
    //                     msg: "修改用户资料成功。"
    //                 })
    //             }
    //         })
    //     })
    // },
    // // 删除
    // remove(user_id) {
    //     return new Promise((resolve, reject) => {
    //         let sql = `delete from  db_user where user_id = "${user_id}"`
    //         db.query(sql, (err, rows) => {
    //             if (err) {
    //                 reject({
    //                     code: -1,
    //                     msg: "删除用户失败。",
    //                     err
    //                 })
    //             } else {
    //                 resolve({
    //                     code: 200,
    //                     msg: "删除用户成功。"
    //                 })
    //             }
    //         })
    //     })
    // },
}